package com.fernfx.xingtan.user;


import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.fernfx.xingtan.Constant;
import com.fernfx.xingtan.common.base.BaseApplication;
import com.fernfx.xingtan.common.entity.user.MemberEntity;
import com.fernfx.xingtan.common.entity.user.UserInfoEntity;
import com.fernfx.xingtan.utils.SPUtil;

/**
 * AccountManager 管理登录用户信息
 */
public class AccountManager {

    /**
     * 存储用户信息
     */
    public static void saveUserInfo(String loginInformation) {
        MemberEntity entity = JSON.parseObject(loginInformation, MemberEntity.class);
        saveUserInfo(entity);
    }

    /**
     * 存储用户信息
     */
    public static void saveUserInfo(MemberEntity entity) {
        if (null != entity ) {
        }
        SPUtil.saveObject(BaseApplication.getInstance(), Constant.UserInfoKeys.USER_INFO, entity);
    }

    /**
     * 获取本地存储的用户信息
     */
    public static MemberEntity getUserInfo() {
        if (null != BaseApplication.memberEntity) {
            return BaseApplication.memberEntity;
        } else {
            MemberEntity entity = (MemberEntity) SPUtil.getObject(BaseApplication.getInstance(), Constant.UserInfoKeys.USER_INFO);
            BaseApplication.memberEntity = entity;
            return entity;
        }
    }

    /**
     * 清空登录的用户信息，hasRecord字段
     */
    public static void clearLoginUserInfo() {
        SPUtil.delete(BaseApplication.getInstance(), Constant.UserInfoKeys.USER_INFO);
    }


    public static boolean isLogin() {
        return null != getUserInfo() && SPUtil.readBoolean(Constant.UserInfoKeys.USER_IS_LOGIN);
    }

    /*
     *保存登录状态
     */
    public static void saveLoginStatus(boolean flag) {
        SPUtil.writeBoolean(Constant.UserInfoKeys.USER_IS_LOGIN,flag);
    }

    /*
     * check token
     */
    public static boolean isExistToken(){
        return isLogin() && !TextUtils.isEmpty(getUserInfo().getObj().getToken()) ? true : false;
    }

    /*
     * 更新本地的手机号
     */
    public static void updateMobilePhone(String mobliePhone){
        if (TextUtils.isEmpty(mobliePhone)) {
            return;
        }
        MemberEntity memberEntity = AccountManager.getUserInfo();
        UserInfoEntity userInfoEntity = memberEntity.getObj();
        userInfoEntity.setMobile(mobliePhone);
        AccountManager.clearLoginUserInfo();
        AccountManager.saveUserInfo(memberEntity);
    }
}
